package com.utooo.service.purchase;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.dao.purchase.OrderDeductionDetailMapper;
import com.utooo.dao.purchase.OrderDeductionMapper;
import com.utooo.dao.purchase.OrderReceiptMapper;
import com.utooo.dao.purchase.OrderReturnDetailMapper;
import com.utooo.dao.purchase.OrderReturnMapper;
import com.utooo.dao.supplier.SupplierOrderDeductionMapper;
import com.utooo.pojo.domain.purchase.order.OrderDeductionDO;
import com.utooo.pojo.domain.purchase.order.OrderDeductionDetailDO;
import com.utooo.pojo.domain.purchase.order.OrderReceiptDO;
import com.utooo.pojo.domain.purchase.order.OrderReturnDO;
import com.utooo.pojo.domain.purchase.order.OrderReturnDetailDO;
import com.utooo.pojo.domain.supplier.execute.SupplierOrderDeductionDO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

@Service
@Slf4j
public class OrderDeductionServiceImpl extends ServiceImpl<OrderDeductionMapper, OrderDeductionDO>
        implements OrderDeductionService {
    @Resource
    private OrderReturnMapper orderReturnMapper;
    @Resource
    private OrderReturnDetailMapper orderReturnDetailMapper;
    @Resource
    private OrderDeductionDetailMapper orderDeductionDetailMapper;
    @Resource
    private SupplierOrderDeductionMapper supplierOrderDeductionMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrderDeduction(String orderReturnId) {
        OrderReturnDO orderReturn = orderReturnMapper
                .selectOne(new LambdaQueryWrapper<OrderReturnDO>()
                        .eq(OrderReturnDO::getId, orderReturnId));
        if (orderReturn == null) {
            log.error("订单退货不存在！{}", orderReturnId);
            return;
        }

        List<OrderReturnDetailDO> orderReturnDetails = orderReturnDetailMapper
                .selectList(new LambdaQueryWrapper<OrderReturnDetailDO>()
                        .eq(OrderReturnDetailDO::getForeignId, orderReturn.getId()));
        if (CollUtil.isEmpty(orderReturnDetails)) {
            log.error("订单退货详情不存在！{}", orderReturnId);
            return;
        }
        // 采购方订单扣款
        OrderDeductionDO orderDeductionDO = new OrderDeductionDO();
        orderDeductionDO.setCompany(orderReturn.getCompany());
        String deductionNo = generateOrderDeductionNo();
        orderDeductionDO.setDeductionNo(deductionNo);
        orderDeductionDO.setDeductionType("1");
        BigDecimal returnAmountIncludingTax = orderReturn.getReturnAmountIncludingTax();
        orderDeductionDO.setAmountIncludingTax(returnAmountIncludingTax);
        this.save(orderDeductionDO);
        String deductionId = orderDeductionDO.getId();
        orderReturnDetails.forEach(i -> {
            OrderDeductionDetailDO orderDeductionDetail = new OrderDeductionDetailDO();
            BeanUtil.copyProperties(i, orderDeductionDetail, IGNORED_PROPERTIES);
            orderDeductionDetail.setForeignId(deductionId);
            orderDeductionDetail.setOrderNo(orderReturn.getOrderNo());
//            orderDeductionDetail.setOrderNoLine(i.getOrderNoLine());
            orderDeductionDetail.setSupplierCode(orderReturn.getSupplierCode());
            orderDeductionDetail.setSupplierName(orderReturn.getSupplierName());
            orderDeductionDetailMapper.insert(orderDeductionDetail);
        });

        // 供应商订单扣款
        SupplierOrderDeductionDO supplierOrderDeductionDO = new SupplierOrderDeductionDO();
        supplierOrderDeductionDO.setCompany(orderReturn.getCompany());
        supplierOrderDeductionDO.setDeductionNo(deductionNo);
        supplierOrderDeductionDO.setDeductionType("1");
        supplierOrderDeductionDO.setAmountIncludingTax(returnAmountIncludingTax);
        supplierOrderDeductionMapper.insert(supplierOrderDeductionDO);
        String supplierOrderDeductionId = supplierOrderDeductionDO.getId();
        orderReturnDetails.forEach(i -> {
            OrderDeductionDetailDO orderDeductionDetail = new OrderDeductionDetailDO();
            BeanUtil.copyProperties(i, orderDeductionDetail, IGNORED_PROPERTIES);
            orderDeductionDetail.setForeignId(supplierOrderDeductionId);
            orderDeductionDetail.setOrderNo(orderReturn.getOrderNo());
//            orderDeductionDetail.setOrderNoLine(i.getOrderNoLine());
            orderDeductionDetail.setSupplierCode(orderReturn.getSupplierCode());
            orderDeductionDetail.setSupplierName(orderReturn.getSupplierName());
            orderDeductionDetailMapper.insert(orderDeductionDetail);
        });
    }

    private String generateOrderDeductionNo() {
        String prefix = "KK";
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<OrderDeductionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(OrderDeductionDO::getDeductionNo, prefix + datePart);
        queryWrapper.orderByDesc(OrderDeductionDO::getDeductionNo);
        queryWrapper.last("LIMIT 1");
        OrderDeductionDO orderDeductionDO = this.getOne(queryWrapper);

        // 生成序列号
        int maxSequence = 0;
        if (orderDeductionDO != null) {
            String deductionNo = orderDeductionDO.getDeductionNo();
            maxSequence = Integer.parseInt(deductionNo.substring((prefix + datePart).length()));
        }
        int nextSequence = maxSequence + 1;
        String sequencePart = String.format("%03d", nextSequence);
        return prefix + datePart + sequencePart;
    }
}